package com.common.service;

import java.util.HashMap;
import java.util.Map;

import javax.xml.namespace.QName;

import org.apache.axis.client.Call;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.aop.framework.AopInfrastructureBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class WebServiceClient implements AopInfrastructureBean {

	@Value("${webServiceType:cfx}")
	private String webServiceType;

	private Map<String, Client> cfxClientMap = new HashMap<String, Client>();

	private JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();

	public String webServiceCall(String wsdlUrl, String cname, String method, String paramName, Object[] params) {
		if (!wsdlUrl.endsWith("?wsdl")) {
			wsdlUrl = wsdlUrl + "?wsdl";
		}
		// 采用cxf实现
		if (webServiceType.equals("cfx")) {
			Client client = cfxClientMap.get(wsdlUrl);
			if (client == null) {
				client = dcf.createClient(wsdlUrl);
				cfxClientMap.put(wsdlUrl, client);
			}
			Object[] result = null;
			try {
				if (StringUtils.isEmpty(cname)) {
					result = client.invoke(method, params);
				} else {
					QName opName = new QName(cname, method);// selectOrderInfo
					result = client.invoke(opName, params);
				}
				if(result==null||result.length==0) {
					log.info("cfx webservice 返回结果为空!");
					return "";
				}
				String resultStr = result[0].toString();
				log.info("cfx webservice call result:" + resultStr);
				return resultStr;
			} catch (Exception e) {
				log.error("cfx webservice 调用url:{}异常", wsdlUrl, e);
			}
		} else {
			// 采用axis服务实现
			org.apache.axis.client.Service webservice = new org.apache.axis.client.Service();
			try {
				org.apache.axis.client.Call call = (Call) webservice.createCall();
				call.setTargetEndpointAddress(new java.net.URL(wsdlUrl));
				call.setOperationName(new QName(cname, method));// 接口方法名
				call.addParameter(new QName(cname, paramName), // 接口方法入参名
						org.apache.axis.encoding.XMLType.SOAP_STRING, javax.xml.rpc.ParameterMode.IN);// 接口的参数
				call.setReturnType(org.apache.axis.encoding.XMLType.SOAP_STRING);// 设置返回类型
				call.setUseSOAPAction(false);
				call.setSOAPActionURI(cname + method);
				String response = (String) call.invoke(params);
				log.info("axis webservic call result:" + response);
				return response;
			} catch (Exception e) {
				e.printStackTrace();
				log.error("axis webservice 调用url:{}异常", wsdlUrl, e);
			}
		}
		return "";
	}
}
